package com.chouren.goandroid.http.parser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileParser extends DataParser<File>{
	private File file;
	
	public FileParser(String path) {
		this(new File(path));
	}
	
	public FileParser(File file) {
		this.file = file;
	}

	@Override
	public File parseData(InputStream is, int len, String charSet)
			throws IOException {
		return streamToFile(is);
	}
	
	private File streamToFile(InputStream is) throws IOException {
		FileOutputStream fos = null;
		try {
			if(file != null && !file.getParentFile().exists()) {
				file.mkdirs();
			}
			fos = new FileOutputStream(file);
			final byte[] temp = new byte[buffSize];
			int length;
			while((length = is.read(temp)) != -1) {
				fos.write(temp, 0, length);
				if(doStatistics) readLength += length;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			fos.close();
		}
		return file;
	}
	
}
